package com.yuerenjf.yuerenjinfu.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.qiniu.android.utils.StringUtils;
import com.yuerenjf.yuerenjinfu.R;
import com.yuerenjf.yuerenjinfu.bean.LoginBean;
import com.yuerenjf.yuerenjinfu.http.Constants;
import com.yuerenjf.yuerenjinfu.http.Xutils;
import com.yuerenjf.yuerenjinfu.utils.CacheUtils;
import com.yuerenjf.yuerenjinfu.utils.CommonUtils;
import com.yuerenjf.yuerenjinfu.utils.ConstantUtils;
import com.yuerenjf.yuerenjinfu.utils.CustomImageSpan;
import com.yuerenjf.yuerenjinfu.utils.ImageUtils;
import com.yuerenjf.yuerenjinfu.utils.MessageTimer;
import com.yuerenjf.yuerenjinfu.utils.SMSContent;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.util.LogUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class RegisterActivity extends BaseActivity {

    private TextView tv_register_login;
    private TextView tv_register_complete;
    private TextView tv_register_code;
    private EditText et_register_username;
    private EditText et_register_pwd;
    private EditText et_register_code;
    private SMSContent smsContent;
    private EditText et_register_invite;

    private TextView tv_register_agreement;
    private boolean isCheck = true;


    private ImageView codeImage;
    EditText codeImageEdit;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        tv_title.setText("用户注册");
        ll_back.setOnClickListener(mOnClickListener);
    }

    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_register_login:
                    startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                    finish();
                    break;
                case R.id.tv_register_code:
                    if (!CommonUtils.isMobileNO(et_register_username.getText().toString())) {
                        Toast.makeText(RegisterActivity.this, "手机号码格式不正确", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (TextUtils.isEmpty(codeImageEdit.getText().toString())) {
                        Toast.makeText(RegisterActivity.this, "请输入右侧图片的数字", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    sendCode(et_register_username.getText().toString());
                    break;
                case R.id.tv_register_complete:
                    if (!CommonUtils.isMobileNO(et_register_username.getText().toString())) {
                        Toast.makeText(RegisterActivity.this, "手机号码格式不正确", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (StringUtils.isNullOrEmpty(codeImageEdit.getText().toString())) {
                        Toast.makeText(RegisterActivity.this, "请输入右侧图片的数字", Toast.LENGTH_SHORT).show();
                        return;
                    }



                    if (et_register_code.getText().toString().equals("")) {
                        Toast.makeText(RegisterActivity.this, "验证码不能为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (!CommonUtils.isPassword(et_register_pwd.getText().toString())) {
                        Toast.makeText(RegisterActivity.this, "密码需8-20位,至少包含字母和数字", Toast.LENGTH_LONG).show();
                        return;
                    }

                    if (!isCheck) {
                        Toast.makeText(RegisterActivity.this, "注册用户需阅读并同意网站协议", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    register();
                    break;
                case R.id.ll_back:
                    finish();
                    break;

                case R.id.tv_register_code_image:
                    getCodeImage();
                    break;
                default:
                    break;
            }
        }
    };

    private void sendCode(String phone) {
        Map<String, String> map = new HashMap<>();
        map.put("phone", phone);
        map.put("imagecode",codeImageEdit.getText().toString());
        Xutils.getInstance().post(RegisterActivity.this, Constants.URL_REGISTER_GET_CODE, map, new Xutils.XCallBack() {
            @Override
            public void onResponse(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    int status = jsonObject.getInt("status");
                    if (status == 200) {
                        Toast.makeText(RegisterActivity.this, "验证码发送成功", Toast.LENGTH_SHORT).show();
                        new MessageTimer(tv_register_code, 90000, 1000).start();

                    } else if (status == 400) {
                        String message = jsonObject.getString("message");
                        Toast.makeText(RegisterActivity.this, message, Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(RegisterActivity.this, "发送失败", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailer(int status, String result){
            }


            @Override
            public void onFinish() {

            }
        });

    }

    private void register() {
        Map<String, String> map = new HashMap<>();
        map.put("phone", et_register_username.getText().toString());
        map.put("password", et_register_pwd.getText().toString());
        map.put("imagecode", codeImageEdit.getText().toString());
        map.put("captcha", et_register_code.getText().toString());
        map.put("pwd", et_register_pwd.getText().toString());
        map.put("invite_code", et_register_invite.getText().toString());
        Xutils.getInstance().post(RegisterActivity.this, Constants.URL_REGISTER, map, new Xutils.XCallBack() {
            @Override
            public void onResponse(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    int status = jsonObject.getInt("status");
                    String message = jsonObject.getString("message");
                    if (status == 200) {
                        LoginBean loginBean = new Gson().fromJson(result, LoginBean.class);

                        String uid = loginBean.getData().getUid();
                        String keep_code = loginBean.getData().getKeep_code();
                        String secret = loginBean.getData().getSecret();

//                        String token = CacheUtils.getString(LoginActivity.this, ConstantUtils.SP_TOKEN);
                        String web_signature = CommonUtils.md5(CommonUtils.md5(CacheUtils.getString(RegisterActivity.this, ConstantUtils.SP_TOKEN) + uid) + secret);
//
                        List<String> stringList = new ArrayList<>();

                        String signature = CommonUtils.md5(CommonUtils.md5(CacheUtils.getString(RegisterActivity.this, ConstantUtils.SP_TOKEN) + uid) + secret);

                        String avatar=loginBean.getData().getAvatar();
                        if(!StringUtils.isNullOrEmpty(avatar)){
                            CacheUtils.setString(RegisterActivity.this, ConstantUtils.SP_AVATAR, loginBean.getData().getAvatar());
                        }

                        CacheUtils.setString(RegisterActivity.this, ConstantUtils.SP_USER_PHONE, et_register_username.getText().toString());
                        CacheUtils.setString(RegisterActivity.this, ConstantUtils.SP_UID, uid);
                        CacheUtils.setString(RegisterActivity.this, ConstantUtils.SP_SECRET, secret);
                        CacheUtils.setString(RegisterActivity.this, ConstantUtils.SP_KEEP_CODE, keep_code);
                        CacheUtils.setString(RegisterActivity.this, ConstantUtils.SP_WEB_SIGNATURE, web_signature);
                        CacheUtils.setString(RegisterActivity.this, ConstantUtils.SP_SIGNATURE, signature);
                        saveUserName();
                        RegisterSuccessActivity.launchActivity(RegisterActivity.this);
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailer(int status, String result) {
                if(status==300){
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(result);
                        JSONObject object = jsonObject.getJSONObject("data");
                        String base64Code= object.getString("img");
                        Bitmap bp= ImageUtils.stringtoBitmap(base64Code);
                        codeImage.setImageBitmap(bp);
                        codeImageEdit.setText("");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFinish() {

            }
        });


    }


    @Override
    protected View getChildView() {
        View view = View.inflate(this, R.layout.activity_register, null);
        tv_register_login = (TextView) view.findViewById(R.id.tv_register_login);
        tv_register_complete = (TextView) view.findViewById(R.id.tv_register_complete);
        tv_register_code = (TextView) view.findViewById(R.id.tv_register_code);
        et_register_username = (EditText) view.findViewById(R.id.et_register_username);
        et_register_pwd = (EditText) view.findViewById(R.id.et_register_pwd);
        et_register_code = (EditText) view.findViewById(R.id.et_register_code);
        tv_register_agreement = (TextView) view.findViewById(R.id.tv_register_agreement);
        et_register_invite = (EditText) view.findViewById(R.id.et_register_invite);
        codeImage= (ImageView) view.findViewById(R.id.tv_register_code_image);
        codeImageEdit = (EditText) view.findViewById(R.id.et_register_code_number_edit);
        codeImage.setOnClickListener(mOnClickListener);
//        tv_register_agreement.setOnClickListener(mOnClickListener);
        tv_register_login.setOnClickListener(mOnClickListener);
        tv_register_complete.setOnClickListener(mOnClickListener);
        tv_register_code.setOnClickListener(mOnClickListener);


        initAgreeLayout(tv_register_agreement, R.drawable.icon_register_selected);
        getCodeImage();
        smsContent = new SMSContent(new Handler(), RegisterActivity.this, et_register_code);
        RegisterActivity.this.getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, smsContent);
        return view;
    }
    private void saveUserName() {
        String sUserName = CacheUtils.getString(RegisterActivity.this, ConstantUtils.SP_USER_NAME);
        if (!sUserName.contains(",")) {
            sUserName = "";
        }
        if (!sUserName.contains(et_register_username.getText().toString())) {
            CacheUtils.setString(RegisterActivity.this, ConstantUtils.SP_USER_NAME, sUserName + et_register_username.getText().toString() + ",");
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.getContentResolver().unregisterContentObserver(smsContent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    private void initAgreeLayout(TextView view, int resource) {
//        Html.ImageGetter imageGetter = new Html.ImageGetter() {
//            @Override
//            public Drawable getDrawable(String source) {
//                int id = Integer.parseInt(source);
//
//                //根据id从资源文件中获取图片对象
//                Drawable d = getResources().getDrawable(id);
//                d.setBounds(0, 0, d.getIntrinsicWidth(),d.getIntrinsicHeight());
//                return d;
//            }
//        };
//        R.drawable.icon_register_selected
        SpannableString spanableInfo = new SpannableString(" 我已阅读并同意");
        CustomImageSpan imageSpan = new CustomImageSpan(this, resource, 2);
        spanableInfo.setSpan(imageSpan, 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spanableInfo.setSpan(new Clickable(imageClickListener),
                0, 1, //设置需要监听的字符串位置
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        view.append(spanableInfo);

        SpannableString spanableInfo2 = new SpannableString("《赚个车网站协议》");
        spanableInfo2.setSpan(new Clickable(click),
                0, 8, //设置需要监听的字符串位置
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spanableInfo2.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.gray_dark)), 0,
                8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);


        view.append(spanableInfo2);
        view.setMovementMethod(LinkMovementMethod.getInstance());
        view.setHighlightColor(getResources().getColor(android.R.color.transparent));
    }

    private View.OnClickListener click = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            WebActivity.launchActivity(RegisterActivity.this, Constants.URL_REGISTER_SAFE);
        }
    };
    private View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            WebActivity.launchActivity(RegisterActivity.this, Constants.URL_REGISTER_INFOSS);
        }
    };
    private View.OnClickListener imageClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            tv_register_agreement.setText("");
            if (isCheck) {

                initAgreeLayout(tv_register_agreement, R.drawable.icon_register_unselect);
            } else {
                initAgreeLayout(tv_register_agreement, R.drawable.icon_register_selected);
            }
            isCheck = !isCheck;
        }
    };


    class Clickable extends ClickableSpan {
        private final View.OnClickListener mListener;

        public Clickable(View.OnClickListener l) {
            mListener = l;
        }

        /**
         * 重写父类点击事件
         */
        @Override
        public void onClick(View v) {
            mListener.onClick(v);
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            super.updateDrawState(ds);
            ds.setUnderlineText(false);// 设置文字下划线不显示
            ds.setColor(getResources().getColor(R.color.dark_title));// 设置字体颜色
            ds.clearShadowLayer();
        }
    }




    private void getCodeImage() {
        Map<String, String> map = new HashMap<>();
        map.put("type","2");
        Xutils.getInstance().get(RegisterActivity.this, Constants.URL_REGISTER_AUTH_CODE, map, new Xutils.XCallBack() {
            @Override
            public void onResponse(String result) {
                LogUtil.i(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    int status = jsonObject.getInt("status");
                    String message = jsonObject.getString("message");
                    if (status == 200) {
                       JSONObject object = jsonObject.getJSONObject("data");
                       String base64Code= object.getString("img");
                       Bitmap bp= ImageUtils.stringtoBitmap(base64Code);
                        codeImage.setImageBitmap(bp);
                        codeImageEdit.setText("");
                    } else  {
                        Toast.makeText(RegisterActivity.this, message, Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailer(int status, String result) {

            }

            @Override
            public void onFinish() {

            }
        });


    }

}
